<template>
  <div class="order-exception">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>异常订单处理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleNavigate('template')">
          <el-icon><Document /></el-icon>处理模板
        </el-button>
        <el-button type="success" @click="handleNavigate('knowledge')">
          <el-icon><Collection /></el-icon>知识库
        </el-button>
        <el-button type="warning" @click="handleNavigate('statistics')">
          <el-icon><TrendCharts /></el-icon>统计分析
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单编号" clearable />
        </el-form-item>
        <el-form-item label="异常类型">
          <el-select v-model="searchForm.exceptionType" placeholder="请选择异常类型" clearable>
            <el-option label="退款纠纷" value="refund" />
            <el-option label="服务投诉" value="complaint" />
            <el-option label="商品问题" value="product" />
            <el-option label="其他异常" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态" clearable>
            <el-option label="待处理" value="pending" />
            <el-option label="处理中" value="processing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理时限">
          <el-select v-model="searchForm.timeLimit" placeholder="请选择处理时限" clearable>
            <el-option label="即将超时" value="urgent" />
            <el-option label="已超时" value="overdue" />
            <el-option label="正常" value="normal" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人">
          <el-select v-model="searchForm.handler" placeholder="请选择处理人" clearable>
            <el-option
              v-for="user in handlerList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 异常订单列表 -->
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>异常订单列表</span>
            <el-tag type="warning" class="ml-2">
              待处理: {{ statistics.pending }}
            </el-tag>
            <el-tag type="danger" class="ml-2">
              即将超时: {{ statistics.urgent }}
            </el-tag>
            <el-tag type="info" class="ml-2">
              已超时: {{ statistics.overdue }}
            </el-tag>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="handleExport">导出记录</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="exceptionList"
        border
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单编号" min-width="180" show-overflow-tooltip />
        <el-table-column prop="exceptionType" label="异常类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.exceptionType)">
              {{ getExceptionTypeLabel(row.exceptionType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="处理状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="timeLimit" label="处理时限" width="120">
          <template #default="{ row }">
            <el-tag :type="getTimeLimitTag(row.timeLimit)">
              {{ getTimeLimitLabel(row.timeLimit) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="handlerName" label="处理人" width="120" />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column prop="updateTime" label="最后处理时间" min-width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="success" 
              link 
              @click="handleProcess(row)"
            >
              处理
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="warning" 
              link 
              @click="handleAssign(row)"
            >
              分配
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="info" 
              link 
              @click="handleTemplate(row)"
            >
              模板
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 异常订单详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="异常订单详情"
      width="800px"
    >
      <div class="exception-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentException.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="异常类型">
            <el-tag :type="getExceptionTypeTag(currentException.exceptionType)">
              {{ getExceptionTypeLabel(currentException.exceptionType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusTag(currentException.status)">
              {{ getStatusLabel(currentException.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理时限">
            <el-tag :type="getTimeLimitTag(currentException.timeLimit)">
              {{ getTimeLimitLabel(currentException.timeLimit) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理人">{{ currentException.handlerName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentException.createTime }}</el-descriptions-item>
          <el-descriptions-item label="异常描述" :span="2">
            {{ currentException.description }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- 处理记录 -->
        <div class="process-records">
          <h3>处理记录</h3>
          <el-timeline>
            <el-timeline-item
              v-for="record in currentException.records"
              :key="record.id"
              :type="getRecordTypeTag(record.type)"
              :timestamp="record.createTime"
            >
              <h4>{{ record.title }}</h4>
              <p>{{ record.content }}</p>
              <p class="handler">处理人：{{ record.handlerName }}</p>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-dialog>

    <!-- 处理异常订单对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="处理异常订单"
      width="600px"
    >
      <el-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        label-width="100px"
      >
        <el-form-item label="处理方式" prop="processType">
          <el-select v-model="processForm.processType" placeholder="请选择处理方式">
            <el-option label="退款处理" value="refund" />
            <el-option label="补偿处理" value="compensation" />
            <el-option label="协商处理" value="negotiation" />
            <el-option label="其他处理" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理结果" prop="result">
          <el-input
            v-model="processForm.result"
            type="textarea"
            :rows="4"
            placeholder="请输入处理结果"
          />
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input
            v-model="processForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleProcessSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配处理人对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配处理人"
      width="500px"
    >
      <el-form
        ref="assignFormRef"
        :model="assignForm"
        :rules="assignRules"
        label-width="100px"
      >
        <el-form-item label="处理人" prop="handlerId">
          <el-select
            v-model="assignForm.handlerId"
            placeholder="请选择处理人"
            filterable
          >
            <el-option
              v-for="user in handlerList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分配说明" prop="remark">
          <el-input
            v-model="assignForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入分配说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssignSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 使用模板对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="选择处理模板"
      width="600px"
    >
      <el-table
        :data="templateList"
        border
        style="width: 100%"
        @row-click="handleTemplateSelect"
      >
        <el-table-column prop="name" label="模板名称" min-width="150" />
        <el-table-column prop="type" label="适用类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.type)">
              {{ getExceptionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="模板内容" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Document, Collection, TrendCharts } from '@element-plus/icons-vue'
import {
  getMerchantOrderExceptionList,
  getMerchantOrderExceptionDetail,
  processMerchantOrderException,
  assignMerchantOrderException,
  getMerchantOrderExceptionTemplateList,
  exportMerchantOrderExceptions,
  getMerchantOrderExceptionStatistics
} from '@/api/merchant'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  exceptionType: '',
  status: '',
  timeLimit: '',
  handler: '',
  dateRange: []
})

// 异常订单列表数据
const loading = ref(false)
const exceptionList = ref([])
const handlerList = ref([])
const statistics = ref({
  pending: 0,
  urgent: 0,
  overdue: 0
})

// 分页信息
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const detailDialogVisible = ref(false)
const processDialogVisible = ref(false)
const assignDialogVisible = ref(false)
const templateDialogVisible = ref(false)
const currentException = ref({})
const templateList = ref([])

// 处理表单
const processFormRef = ref(null)
const processForm = reactive({
  id: '',
  processType: '',
  result: '',
  remark: ''
})

// 分配表单
const assignFormRef = ref(null)
const assignForm = reactive({
  id: '',
  handlerId: '',
  remark: ''
})

// 表单验证规则
const processRules = {
  processType: [
    { required: true, message: '请选择处理方式', trigger: 'change' }
  ],
  result: [
    { required: true, message: '请输入处理结果', trigger: 'blur' },
    { min: 2, max: 500, message: '长度在 2 到 500 个字符', trigger: 'blur' }
  ]
}

const assignRules = {
  handlerId: [
    { required: true, message: '请选择处理人', trigger: 'change' }
  ]
}

// 获取异常订单列表
const getExceptionList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderExceptionList({
      ...searchForm,
      page: page.current,
      size: page.size
    })
    exceptionList.value = data.list
    page.total = data.total
  } catch (error) {
    console.error('获取异常订单列表失败:', error)
    ElMessage.error('获取异常订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantOrderExceptionStatistics()
    statistics.value = data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 页面导航
const handleNavigate = (type) => {
  router.push(`/merchant/order-exception/${type}`)
}

// 搜索
const handleSearch = () => {
  page.current = 1
  getExceptionList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  handleSearch()
}

// 查看详情
const handleView = async (row) => {
  try {
    const { data } = await getMerchantOrderExceptionDetail(row.id)
    currentException.value = data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取异常订单详情失败:', error)
  }
}

// 处理异常订单
const handleProcess = (row) => {
  currentException.value = row
  processForm.id = row.id
  processForm.processType = ''
  processForm.result = ''
  processForm.remark = ''
  processDialogVisible.value = true
}

// 提交处理
const handleProcessSubmit = async () => {
  if (!processFormRef.value) return
  
  try {
    await processFormRef.value.validate()
    await processMerchantOrderException(processForm)
    ElMessage.success('处理成功')
    processDialogVisible.value = false
    getExceptionList()
    getStatistics()
  } catch (error) {
    console.error('处理异常订单失败:', error)
  }
}

// 分配处理人
const handleAssign = (row) => {
  currentException.value = row
  assignForm.id = row.id
  assignForm.handlerId = ''
  assignForm.remark = ''
  assignDialogVisible.value = true
}

// 提交分配
const handleAssignSubmit = async () => {
  if (!assignFormRef.value) return
  
  try {
    await assignFormRef.value.validate()
    await assignMerchantOrderException(assignForm)
    ElMessage.success('分配成功')
    assignDialogVisible.value = false
    getExceptionList()
  } catch (error) {
    console.error('分配处理人失败:', error)
  }
}

// 使用模板
const handleTemplate = async (row) => {
  currentException.value = row
  try {
    const { data } = await getMerchantOrderExceptionTemplateList()
    templateList.value = data
    templateDialogVisible.value = true
  } catch (error) {
    console.error('获取处理模板列表失败:', error)
  }
}

// 选择模板
const handleTemplateSelect = (row) => {
  processForm.processType = row.processType
  processForm.result = row.content
  templateDialogVisible.value = false
  processDialogVisible.value = true
}

// 导出记录
const handleExport = async () => {
  try {
    await exportMerchantOrderExceptions(searchForm)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出异常订单记录失败:', error)
  }
}

// 获取异常类型标签类型
const getExceptionTypeTag = (type) => {
  const typeMap = {
    refund: 'danger',
    complaint: 'warning',
    product: 'error',
    other: 'info'
  }
  return typeMap[type] || ''
}

// 获取异常类型标签文本
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    refund: '退款纠纷',
    complaint: '服务投诉',
    product: '商品问题',
    other: '其他异常'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTag = (status) => {
  const statusMap = {
    pending: 'warning',
    processing: 'primary',
    completed: 'success',
    closed: 'info'
  }
  return statusMap[status] || ''
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    closed: '已关闭'
  }
  return statusMap[status] || status
}

// 获取处理时限标签类型
const getTimeLimitTag = (timeLimit) => {
  const typeMap = {
    urgent: 'warning',
    overdue: 'danger',
    normal: 'success'
  }
  return typeMap[timeLimit] || ''
}

// 获取处理时限标签文本
const getTimeLimitLabel = (timeLimit) => {
  const typeMap = {
    urgent: '即将超时',
    overdue: '已超时',
    normal: '正常'
  }
  return typeMap[timeLimit] || timeLimit
}

// 获取处理记录类型标签
const getRecordTypeTag = (type) => {
  const typeMap = {
    create: 'primary',
    assign: 'warning',
    process: 'success',
    close: 'info'
  }
  return typeMap[type] || ''
}

// 分页大小变化
const handleSizeChange = (val) => {
  page.size = val
  getExceptionList()
}

// 页码变化
const handleCurrentChange = (val) => {
  page.current = val
  getExceptionList()
}

onMounted(() => {
  getExceptionList()
  getStatistics()
})
</script>

<style lang="scss" scoped>
.order-exception {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }

    .header-actions {
      display: flex;
      gap: 10px;
    }
  }

  .search-card {
    margin-bottom: 20px;
  }

  .list-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        align-items: center;
        gap: 10px;

        .ml-2 {
          margin-left: 10px;
        }
      }
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .exception-detail {
    .process-records {
      margin-top: 20px;

      h3 {
        margin-bottom: 15px;
        font-size: 16px;
        font-weight: 500;
      }

      .handler {
        margin-top: 5px;
        color: #666;
        font-size: 13px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 